// 引入第三方模块
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const session = require("express-session");

// 创建连接池
var pool = mysql.createPool({
    host:"127.0.0.1",
    user:"root",
    password:"",
    port:3306,
    database:"xz",
    connectionLimit:15
});

// 创建服务器
var server = express();
//跨域
server.use(cors({
    origin:['http://127.0.0.1:8080',
            'http://localhost:8080'],
    credentials:true
}))

// session
server.use(session({
    secret:"128位字符串",
    resave:true,
    saveUninitialized:true
}));

//静态目录
server.use(express.static("public"));
// 监听端口
server.listen(3000);

server.get("/login",(req,res)=>{
    // 获得参数
    var obj = req.query;
    var uname = obj.uname;
    var upwd = obj.upwd;
    //编写sql
    var sql = "SELECT id FROM xz_login WHERE uname=? AND upwd = md5(?)";
    pool.query(sql,[uname,upwd],(err,result)=>{
        if(err) throw err;
        if(result.length > 0){
            // 将用户的uid保存到sassion对象中
            req.session.uid = result[0].id;
            res.send({node:1,msg:"登录成功"})
        }else{
            res.send({node:-1,msg:"用户名或密码错误"})
        }
    })
})
//商品的分页显示
server.get("/product",(req,res)=>{
    var pnum = req.query.pnum; //页码
    var pSize = req.query.pageSize;//每页显示个数
    //设置默认值
    if(!pnum){ pnum = 1 }
    if(!pSize){ pSize = 10 }
    //sql
    var sql = "SELECT lid,title,img_url,price FROM xz_laptop LIMIT ?,?";
    pSize = parseInt(pSize);
    var startline = (pnum - 1)* pSize;//起始查询行数
    pool.query(sql,[startline,pSize],(err,result)=>{
        if(err) throw err;
        var obj = {code:1,msg:"查询成功",data:result};
        //查询总行数
        var sql1 = "SELECT count(*) AS c FROM xz_laptop";
        pool.query(sql1,(err,result1)=>{
            if(err) throw err;
            obj.count = result1[0].c;
            res.send(obj);
        });
    })
});

//查询指定用户的购物车
server.get("/cart",(req,res)=>{
    var uid = req.session.uid;
    if(!uid){
        res.send({code:-1,msg:"请先登录"});
        return;
    }
    var sql = "SELECT xz_cart.id,uname,img_url,price,title,count FROM xz_login,xz_cart WHERE xz_login.id=xz_cart.uid=?"
    pool.query(sql,[uid],(err,result)=>{
        if(err) throw err;
        res.send({code:1,msg:result});
    });
});

server.get("/updcount",(req,res)=>{
    var id = req.query.lid;
    var count = req.query.count1;
    var sql = "UPDATE xz_cart SET count=? WHERE id=?";
    pool.query(sql,[count,id],(err,result)=>{
        if(err) throw err;
        res.send({code:1});
    })
});